package com.lihanjin.mqtt;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.lihanjin.mqtt.services.MyMqttService;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    ImageView[] imageViews = new ImageView[5];//图标数量
    Object[] mmps = new Object[]{R.mipmap.i1,R.mipmap.i2,R.mipmap.i3,R.mipmap.i4,R.mipmap.i5};//图标资源
    String[] userIds = new String[5];//用户ID
    int myTag = 0;//当前用户可拖动图标
    private float downX;
    private float downY;
    float downViewX = 0;
    long times = 0;
    LocationReceiver locationReceiver;
    MyMqttService myMqttService;
    String token;
    String uniqueId;//自动生成
    String clientId;//设备ID
    //配置信息（注册环信账号进控制台获取自己的补上）- 不配置也可以跑起来 :)
    String apiUrl = "https://a1.easemob.com";
    String appKey = "xxxxxx#mqtt-test";
    //mqtt
    String appId = "xxxxxx";
    String host = "tcp://xxxxxx.cn1.mqtt.chat:1883";
    String topic = "ease-mqtt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        setContentView(R.layout.activity_main);
        clientId = System.currentTimeMillis()+"@"+appId;
        //为了方便在MainActivity调用网络注册用户或请求token做的兼容
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        try{
            register();//注册用户[重复也不理]
            getToken();//获取token
        }catch (Exception e){
        }
        if(token!=null&& !"".equals(token)){//token缓不缓存再说吧
            Toast.makeText(MainActivity.this, "环信MQTT...", Toast.LENGTH_SHORT).show();
            SharedPreferences preferences = getSharedPreferences("ease_mqtt",Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("HOST", host);
            editor.putString("USERNAME", "test001");
            editor.putString("PASSWORD", token);
            editor.putString("PUBLISH_TOPIC", topic);
            editor.putString("RESPONSE_TOPIC", topic);
            editor.putString("CLIENTID", clientId);
            editor.putBoolean("usePwd", true);//校验用户名和密码
            editor.commit();
        }
        if (!isServiceRunning("com.lihanjin.mqtt.services.MyMqttService")){
            myMqttService = new MyMqttService();
            myMqttService.startService(this); //开启服务
        }
        //注册广播监听
        locationReceiver = new LocationReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("location.reportsucc");
        registerReceiver(locationReceiver, filter);

        //添加删除图标
        ImageView opView =  (ImageView)this.findViewById(R.id.op);
        opView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //移除图标
                if(myTag>0){
                    opView.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.add));
                    if(imageViews[myTag-1]!=null){
                        imageViews[myTag-1].setVisibility(View.GONE);
                        imageViews[myTag-1] = null;
                    }
                    myTag = 0;
                    Toast.makeText(MainActivity.this, "移除了你的图标!" , Toast.LENGTH_SHORT).show();
                    //移除公告
                    JSONObject json = new JSONObject();
                    json.put("o","-");
                    json.put("u",clientId);
                    myMqttService.response(json.toJSONString());
                    return;
                }
                //看还有没有空位加个图标
                boolean flag = false;
                for(int i=0;i<imageViews.length;i++){
                    if(imageViews[i]==null){
                        flag = true;
                        myTag = i+1;
                        imageViews[i] = addImg(i,"mine");
                        opView.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.del));
                        Toast.makeText(MainActivity.this, "添加了一个图标!可以拖动试试了" , Toast.LENGTH_SHORT).show();
                        //添加公告
                        JSONObject json = new JSONObject();
                        json.put("t",myTag);
                        json.put("o","+");
                        json.put("u",clientId);
                        myMqttService.response(json.toJSONString());
                        return;
                    }
                }
                if(!flag){
                    Toast.makeText(MainActivity.this, "没有可添加的图标!" , Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    @Override
    protected void onDestroy() {
        unregisterReceiver(locationReceiver);
        super.onDestroy();
    }
    /**
     * 注册用户(默认密码为1)
     */
    private void register() {
        JSONObject json = new JSONObject();
        json.put("username","test001");
        json.put("password","1");
        json.put("nickname","");
        try{
            String rStr = httpPost(apiUrl+"/"+appKey.replace("#","/")+"/users",json.toJSONString());
//            Toast.makeText(MainActivity.this, "注册用户:"+rStr, Toast.LENGTH_LONG).show();
        }catch (Exception e){}
    }
    /**
     * 用户名和密码请求获取token
     */
    private void getToken() {
        JSONObject json = new JSONObject();
        json.put("username","test001");
        json.put("password","1");
        json.put("grant_type","password");
        json.put("timestamp",System.currentTimeMillis());
        String rStr = httpPost(apiUrl+"/"+appKey.replace("#","/")+"/token",json.toJSONString());
//        Toast.makeText(MainActivity.this, "获取token"+rStr, Toast.LENGTH_LONG).show();
        JSONObject jsonObject = JSONObject.parseObject(rStr);
        token = jsonObject.getString("access_token");
    }

    /**
     * 加个图形自己玩
     */
    private ImageView addImg(int i,String user){
        FrameLayout contentView =  (FrameLayout)this.findViewById(R.id.box);
        ImageView imageView = new ImageView(this);
        //创建图片的长宽
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(150, 150));
        imageView.setLayoutParams(lp);  //设置图片的大小
        imageView.setTag(i+1);

        imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),(int)mmps[i]));
        contentView.addView(imageView);
        if(!"mine".equals(user)){
            userIds[i] = user;
            return imageView;//不是当前用户添加的，不需要拖动事件
        }
        //获取屏幕宽度
        WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        final int with = outMetrics.widthPixels;
        final int height = outMetrics.heightPixels;
        //只能动一个图形
        imageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.bringToFront();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //按下
                        downX = event.getX();
                        downY = event.getY();
                        downViewX = v.getX();
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        //移动
                        //移动的距离
                        float moveX = event.getX() - downX;// event.getX() 移动的X距离
                        float moveY = event.getY() - downY;// event.getY() 移动的Y距离
                        //当前view= X,Y坐标
                        float viewX = v.getX();
                        float viewY = v.getY();
                        //view的宽高
                        int viewHeigth = v.getWidth();
                        int viewWidth = v.getHeight();

                        //X当超出屏幕,取最大值
                        if (viewX + moveX + viewWidth > with) {
                            //靠右
                            v.setX(with - viewWidth);
                        } else if (viewX + moveX <= 0) {
                            //靠右
                            v.setX(0);
                        } else {
                            //正常
                            v.setX(viewX + moveX);
                        }
                        //Y当超出屏幕,取最大值
                        if (viewY + moveY + viewHeigth > height) {
                            //靠下
                            v.setY(height - viewHeigth);
                        } else if (viewY + moveY <= 0) {
                            //靠上
                            v.setY(0);
                        } else {
                            //正常
                            v.setY(viewY + moveY);
                        }
                        //节拍
                        if(System.currentTimeMillis()-times>200){
                            times = System.currentTimeMillis();
                            JSONObject json = new JSONObject();
                            json.put("t",v.getTag());
                            json.put("o","mv");
                            json.put("x",viewX + moveX);
                            json.put("y",viewY + moveY);
                            myMqttService.response(json.toJSONString());
                        }
                        return true;
                    case MotionEvent.ACTION_UP:
                        //松手
                        JSONObject json = new JSONObject();
                        json.put("t",v.getTag());
                        json.put("o","mv");
                        json.put("x",v.getX());
                        json.put("y",v.getY());
                        myMqttService.response(json.toJSONString());
                }

                return false;
            }
        });
        return imageView;
    }
    /**
     * httpPost 异步
     */
    private void httpPostAsync(String url,String params,Callback callback) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, params))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(callback);
    }
    /**
     * httpPost 异步
     */
    private String httpPost(String url,String params) {
        String rStr = "";
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, params))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);

        try {
            Response response = call.execute();
            rStr = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rStr;
    }

    /**
     * 判断服务是否运行
     */
    private boolean isServiceRunning(final String className) {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> info = activityManager.getRunningServices(Integer.MAX_VALUE);
        if (info == null || info.size() == 0) return false;
        for (ActivityManager.RunningServiceInfo aInfo : info) {
            if (className.equals(aInfo.service.getClassName())) return true;
        }
        return false;
    }

    //内部类，实现BroadcastReceiver
    public class LocationReceiver extends BroadcastReceiver {
        //必须要重载的方法，用来监听是否有广播发送
        @Override
        public void onReceive(Context context, Intent intent) {
            String intentAction = intent.getAction();
            if (intentAction.equals("location.reportsucc")) {
                //处理收到消息
                JSONObject json= JSONObject.parseObject(intent.getStringExtra("msg"));
                String o = json.getString("o");
                if("ol".equals(o)){ //处理上线消息
                    //回复当前用户占用
                    JSONObject rJson = new JSONObject();
                    rJson.put("t",myTag);
                    rJson.put("o","+");
                    rJson.put("u",clientId);
                    myMqttService.response(json.toJSONString());
                }
                if("+".equals(o)){ //处理添加消息
                    int i = json.getIntValue("t");
                    if(myTag!=i){
                        if(imageViews[i-1]==null){
                            String u = json.getString("u");
                            imageViews[i-1] = addImg(i-1,u);
                        }
                    }
                }
                if("-".equals(o)){//处理移除消息
                    String u = json.getString("u");
                    for(int i=0;i<userIds.length;i++){
                        if(u.equals(userIds[i])){
                            userIds[i] = null;
                            if(imageViews[i]!=null){
                                imageViews[i].setVisibility(View.GONE);
                                imageViews[i] = null;
                            }
                        }
                    }
                }
                if("mv".equals(o)){
                    int i = json.getIntValue("t");
                    if(myTag!=i){
                        if(imageViews[i-1]!=null){
                            imageViews[i-1].setX(json.getFloat("x"));
                            imageViews[i-1].setY(json.getFloat("y"));
                        }
                    }
                }
            }
        }
    }
}